<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Title_FormItem"
								prop="Entity.Title"
								:rules="[{ required: true, message: '招聘岗位为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="招聘岗位" tooltip="招聘发布的岗位" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Title" clearable class="width100" placeholder="请输入岗位，如：XXXX岗位招聘"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_Description_FormItem" prop="Entity.Description">
								<template #label>
									<WtmLabelTooltip label="岗位描述" tooltip="岗位的详细描述" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Description" type="textarea" :rows="3" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>招聘信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_HireNumber_FormItem"
								prop="Entity.HireNumber"
								:rules="[{ required: true, message: '招聘人数为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="招聘人数" tooltip="本岗位计划招聘人数" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.HireNumber" clearable class="width100" disabled></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ExpectedDate_FormItem" prop="Entity.ExpectedDate">
								<template #label>
									<WtmLabelTooltip label="到岗时间" tooltip="期望人员到岗的时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ExpectedDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" type="textarea" :rows="3" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>岗位信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EducationRequirement_FormItem" prop="Entity.EducationRequirement">
								<template #label>
									<WtmLabelTooltip label="学历要求" tooltip="最低学历要求" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EducationRequirement" clearable class="width100">
									<el-option key="小学" value="小学" label="小学"></el-option>
									<el-option key="初中" value="初中" label="初中"></el-option>
									<el-option key="高中" value="高中" label="高中"></el-option>
									<el-option key="中专" value="中专" label="中专"></el-option>
									<el-option key="大专" value="大专" label="大专"></el-option>
									<el-option key="本科" value="本科" label="本科"></el-option>
									<el-option key="研究生" value="研究生" label="研究生"></el-option>
									<el-option key="硕士" value="硕士" label="硕士"></el-option>
									<el-option key="博士" value="博士" label="博士"></el-option>
									<el-option key="博士后" value="博士后" label="博士后"></el-option>
									<el-option key="博士研究生" value="博士研究生" label="博士研究生"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_MajorRequirement_FormItem" prop="Entity.MajorRequirement">
								<template #label>
									<WtmLabelTooltip label="专业要求" tooltip="所需专业方向" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.MajorRequirement"
									clearable
									class="width100"
									placeholder="请输入专业要求，如：计算机相关专业"
								></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_GenderRequirement_FormItem" prop="Entity.GenderRequirement">
								<template #label>
									<WtmLabelTooltip label="性别要求" tooltip="岗位对性别的要求" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.GenderRequirement" clearable class="width100">
									<el-option key="男" value="男" label="男"></el-option>
									<el-option key="女" value="女" label="女"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_AgeRequirement_FormItem" prop="Entity.AgeRequirement">
								<template #label>
									<WtmLabelTooltip label="年龄要求" tooltip="岗位对年龄的要求" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.AgeRequirement" clearable class="width100" placeholder="例如：25-35岁"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_JobRequirement_FormItem" prop="Entity.JobRequirement">
								<template #label>
									<WtmLabelTooltip label="岗位要求" tooltip="岗位的具体要求" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.JobRequirement" type="textarea" :rows="4" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OtherRequirement_FormItem" prop="Entity.OtherRequirement">
								<template #label>
									<WtmLabelTooltip label="其他要求" tooltip="除上述外的其他要求" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.OtherRequirement"
									type="textarea"
									:rows="3"
									clearable
									class="width100"
									placeholder="请输入其他要求，如工作经验、技能证书等"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>待遇信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SalaryRange_FormItem" prop="Entity.SalaryRange">
								<template #label>
									<WtmLabelTooltip label="薪资范围" tooltip="薪资待遇范围" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.SalaryRange" clearable class="width100" placeholder="例如：8000-12000元/月"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Benefits_FormItem" prop="Entity.Benefits">
								<template #label>
									<WtmLabelTooltip label="福利待遇" tooltip="福利待遇说明" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.Benefits"
									type="textarea"
									:rows="3"
									clearable
									class="width100"
									placeholder="请输入福利待遇，如五险一金、年终奖、带薪假期等"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>发布信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_PublishStartDate_FormItem" prop="Entity.PublishStartDate">
								<template #label>
									<WtmLabelTooltip label="发布开始时间" tooltip="招聘信息发布开始时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.PublishStartDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_PublishEndDate_FormItem" prop="Entity.PublishEndDate">
								<template #label>
									<WtmLabelTooltip label="发布结束时间" tooltip="招聘信息发布结束时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.PublishEndDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>联系信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ContactPerson_FormItem" prop="Entity.ContactPerson">
								<template #label>
									<WtmLabelTooltip label="联系人" tooltip="招聘联系人" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ContactPerson" clearable class="width100" placeholder="请输入联系人姓名"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ContactPhone_FormItem" prop="Entity.ContactPhone">
								<template #label>
									<WtmLabelTooltip label="联系电话" tooltip="招聘联系电话" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ContactPhone" clearable class="width100" placeholder="请输入联系电话"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ContactEmail_FormItem" prop="Entity.ContactEmail">
								<template #label>
									<WtmLabelTooltip label="联系邮箱" tooltip="招聘联系邮箱" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ContactEmail" clearable class="width100" placeholder="请输入联系邮箱"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :disabled="true" />
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysHrRecruitPublishRequestBillApi as api } from '/@/views/hr/syshrrecruitpublishrequestbill/api';
import other from '/@/utils/other';
import { ISysHrRecruitPublishRequestBillVm } from '/@/views/hr/syshrrecruitpublishrequestbill/api/interface';
import { IViewModel } from '/@/types/common';

const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
	CANCEL: '取消',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

const stateData = reactive<IViewModel<ISysHrRecruitPublishRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Title: null,
			Description: null,
			HireNumber: 0,
			ExpectedDate: null,
			JobRequirement: null,
			EducationRequirement: null,
			MajorRequirement: null,
			GenderRequirement: null,
			AgeRequirement: null,
			OtherRequirement: null,
			SalaryRange: null,
			Benefits: null,
			JobPositionId: null,
			PublishStartDate: null,
			PublishEndDate: null,
			IsExternalPublish: false,
			ContactPerson: null,
			ContactPhone: null,
			ContactEmail: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			OrgId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		},

		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysJobPositions: [],
	AllSysGroups: [],
	AllSysOrgs: [],
});

const canSubmit = computed(() => stateData.vmModel.Entity.BillStatus === BILL_STATUS.DRAFT);
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

const handleApiResponse = (response: any, isSubmit = false) => {
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
	}
	loading.value = false;
};
// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		false
	);
};

// 提交
const onSubmit = () => {
	if (!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING) {
		stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
	}
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		true
	);
};

// 同意
const onAgree = () => {
	handleApproval(BUTTON_TEXTS.AGREE);
};

// 拒绝
const onReject = () => {
	handleApproval(BUTTON_TEXTS.REJECT);
};

const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	handleApiRequest(
		() => api().approve(stateData.vmModel, ''),
		() => {},
		true
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysHrRecruitPublishRequestBill/GetSysJobPositions', [], false).then((x) => (stateData.AllSysJobPositions = x)),
		other.getSelectList('/api/SysHrRecruitPublishRequestBill/GetSysGroups', [], false).then((x) => (stateData.AllSysGroups = x)),
		other.getSelectList('/api/SysHrRecruitPublishRequestBill/GetSysOrgs', [], false).then((x) => (stateData.AllSysOrgs = x)),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => other.setValue(stateData.vmModel, x)),
	]);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !isInAudit.value, // 非审批状态时显示保存按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value && !isInAudit.value, // 草稿状态且非审批时显示提交
		},
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示同意
		},
		{
			text: BUTTON_TEXTS.CANCEL,
			type: 'danger',
			onClick: onReject,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示拒绝
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true, // 始终显示关闭按钮
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
